import React, { Component } from "react";
import { deepCopy, messages, removeArrayItemByKey, ManuelResizeWindow } from "share/common";
import { Button, Input, Modal, Select } from "antd";
import "styles/data-center/report-distribution/visible-field-comp.scss";
import "styles/data-center/report/universal-report/single-link-comp.scss";
import SingleAttribute from "../../report/universal-report/components/custom-export-setting/single-attribute";
import Muuri from "muuri";
import debounce from "lodash.debounce";

const Option = Select.Option;

class VisibleFieldComp extends Component {
  constructor(props) {
    super(props);
    this.state = {
      modalVisible: false,
      SelectValue: undefined,
      currentLinkFields: [],
      realChooseFields: [],
      SearchKeyWord: "",
    };
    this.targetGrid = null;
    this.attrGrid = null;
    this.realFilter = debounce(this.realFilter, 300);
    this.handleItemMouseOver = debounce(this.handleItemMouseOver, 300);
    this.handleDestroyClose = debounce(this.handleDestroyClose, 300);
    this.resizeWindow = debounce(ManuelResizeWindow, 300);
  }

  componentWillMount() {}

  componentDidMount() {
    this.setValues();
  }

  componentWillReceiveProps(nextProps) {
    this.setValues(nextProps.value);
  }

  setValues = (newValue = this.props.value) => {
    const { visibleField } = this.props;
    if (newValue === undefined) {
      this.setState(
        {
          SelectValue: {
            label:
              visibleField &&
              visibleField.find((item) => item.permission_prop === "all_field_show") &&
              visibleField.find((item) => item.permission_prop === "all_field_show").permission_desc,
            key: "all_field_show",
          },
        },
        this.dispatchChange
      );
    } else if (newValue.length === 1 && newValue[0].distributionMode === "all_field_show") {
      this.setState({
        SelectValue: {
          label: newValue[0].permission_desc,
          key: newValue[0].distributionMode,
        },
      });
    } else if (newValue.length >= 1) {
      this.setState({
        SelectValue: {
          label: newValue[0].permission_desc,
          key: newValue[0].distributionMode,
        },
        realChooseFields: newValue.map((item) => {
          item.slaveColumnId = item.reportColumnId;
          item.slaveColumnDisplayName = item.reportColumnName;
          return item;
        }),
      });
    }
  };

  getMuuriItemKeyArray = (grid) => {
    const itemIds = grid.getItems().map((item) => {
      return item.getElement().getAttribute("data-id");
    });
    return itemIds;
  };

  initTargetMuuri = (List) => {
    if (this.targetGrid) {
      const dataArray = this.getMuuriItemKeyArray(this.targetGrid);
      List.forEach((item) => {
        const target = dataArray.find((slaveColumnId) => item.slaveColumnId === slaveColumnId);
        if (target === undefined) {
          const items = this.targetGrid.add(document.getElementById(`${item.slaveColumnId}-current`), {
            index: -1,
            active: false,
          });
          this.targetGrid.show(items);
        }
      });
      return;
    }
    this.targetGrid = new Muuri(".link-list", {
      dragEnabled: false,
      dragContainer: document.getElementById("custom-report-drag-container"),
      dragSort: () => {
        return [this.targetGrid];
      },
      dragStartPredicate: {
        distance: 5,
        delay: 0,
      },
      dragPlaceholder: {
        enabled: true,
      },
      itemPlaceholderClass: "muuri-item-placeholder-attr",
      itemReleasingClass: "muuri-item-releasing-attr",
      itemDraggingClass: "muuri-item-dragging-attr",
    }).on("dragReleaseEnd", (data) => {});
  };

  initAttrMuuri = (List = []) => {
    if (this.attrGrid) {
      const dataArray = this.getMuuriItemKeyArray(this.attrGrid);
      List.forEach((item) => {
        const target = dataArray.find((id) => `${item.id}` === id.toString());
        if (target === undefined) {
          const items = this.attrGrid.add(document.getElementById(`${item.id}-list`), { index: -1, active: false });
          this.attrGrid.show(items);
        }
      });
      return;
    }
    this.attrGrid = new Muuri(".muuri-list-box", {});
  };

  handleSearchModalAttributes = (e) => {
    this.setState({ SearchKeyWord: e || "" }, () => {
      this.realFilter(e);
    });
  };

  realFilter = (e) => {
    this.attrGrid.filter((item) => {
      return item.getElement().children[0].innerText.indexOf(e) !== -1;
    });
  };

  modalSearchOnChange = (e) => {
    e.persist();
    this.handleSearchModalAttributes(e.target.value);
  };

  onSelectChange = (e) => {
    this.setState({ SelectValue: e, realChooseFields: [] }, this.dispatchChange);
  };

  dispatchChange = () => {
    const { SelectValue, realChooseFields } = this.state;
    const { onChange } = this.props;
    let result = [];
    if (SelectValue.key === "all_field_show") {
      result = [
        {
          distributionMode: SelectValue.key,
          distributionModeDesc: SelectValue.label,
        },
      ];
    } else {
      result = realChooseFields.map((item) => {
        return {
          distributionMode: SelectValue.key,
          distributionModeDesc: SelectValue.label,
          reportColumnId: item.slaveColumnId,
          reportColumnName: item.slaveColumnDisplayName,
          id: item.id,
        };
      });
    }
    onChange && onChange(result);
  };

  handleModalClose = () => {
    this.setState({ modalVisible: false }, () => {
      this.handleDestroyClose();
    });
  };

  handleDestroyClose = () => {
    this.attrGrid.remove(this.attrGrid.getItems(), { removeElements: false });
    this.targetGrid.remove(this.targetGrid.getItems(), {
      removeElements: false,
    });
    this.setState({ currentLinkFields: [], SearchKeyWord: "" });
  };

  handleSelectLink = () => {
    const { currentLinkFields } = this.state;
    this.setState({ realChooseFields: currentLinkFields }, () => {
      this.handleModalClose();
      this.dispatchChange();
    });
  };

  showModal = () => {
    this.setState({ modalVisible: true, currentLinkFields: deepCopy(this.state.realChooseFields) }, () => {
      this.initAttrMuuri(this.props.reportFields);
      this.initTargetMuuri(this.state.currentLinkFields);
      this.resizeWindow();
    });
  };

  addAttributeToTarget = (e, item) => {
    e.stopPropagation();
    e.preventDefault();
    const { currentLinkFields } = this.state;
    currentLinkFields.push({
      slaveColumnId: item.id,
      slaveColumnDisplayName: item.columnDisplayName,
    });
    this.setState({ currentLinkFields }, () => {
      const items = this.targetGrid.add(document.getElementById(`${item.id}-current`), { index: -1, active: false });
      this.targetGrid.show(items);
    });
  };

  chooseAll = (e) => {
    e.preventDefault();
    const { reportFields } = this.props;
    const { currentLinkFields, SearchKeyWord } = this.state;
    reportFields
      .filter((item) => item.columnDisplayName.indexOf(SearchKeyWord) !== -1)
      .forEach((field) => {
        if (!currentLinkFields.find((item) => item.slaveColumnId === field.id)) {
          currentLinkFields.push({
            slaveColumnId: field.id,
            slaveColumnDisplayName: field.columnDisplayName,
          });
          this.setState({ currentLinkFields }, () => {
            const items = this.targetGrid.add(document.getElementById(`${field.id}-current`), {
              index: -1,
              active: false,
            });
            this.targetGrid.show(items);
          });
        }
      });
  };

  unChooseAll = (e) => {
    e.preventDefault();
    const deleteItems = this.targetGrid.getItems();
    this.targetGrid.remove(deleteItems, { removeElements: false });
    this.setState({ currentLinkFields: [], hoverItem: {} });
  };

  handleItemMouseOver = (item) => {
    this.setState({ hoverItem: item });
  };

  handleItemMouseLeave = () => {
    this.handleItemMouseOver.cancel();
    this.setState({ hoverItem: {} });
  };

  deleteFieldItem = (widget, out, index) => {
    this.handleItemMouseOver.cancel();
    if (out) {
      const { realChooseFields } = this.state;
      const newRealChooseFields = removeArrayItemByKey(realChooseFields, widget, "slaveColumnId");
      this.setState({ realChooseFields: newRealChooseFields }, () => {
        this.dispatchChange();
      });
    } else {
      const currentLinkFields = removeArrayItemByKey(this.state.currentLinkFields, widget, "slaveColumnId");
      const deleteItem = this.targetGrid.getItems().filter((filterItem) => {
        return filterItem.getElement().getAttribute("data-id") === widget.slaveColumnId.toString();
      });
      this.targetGrid.remove(deleteItem, { removeElements: false });
      this.setState({ currentLinkFields, hoverItem: {} });
    }
  };

  render() {
    const { SelectValue, modalVisible, currentLinkFields, realChooseFields, hoverItem, SearchKeyWord } = this.state;
    const { visibleField, permissionDetail, reportFields, loading } = this.props;
    return (
      <div className={"visible-field-comp"}>
        <Select
          value={SelectValue}
          labelInValue
          onChange={this.onSelectChange}
          style={{ width: "66%" }}
          getPopupContainer={(triggerNode) => triggerNode.parentNode}
          placeholder={messages("common.select") /*请选择*/}
        >
          {visibleField.map((option) => {
            return (
              <Option key={option.id} value={option.permission_prop}>
                {option.permission_desc}
              </Option>
            );
          })}
        </Select>
        <div className={"add-field-btn"}>
          {SelectValue && SelectValue.key === "part_field_show" && (
            <Button onClick={this.showModal} loading={loading} type={"primary"}>
              {messages("basic-10.key245") /*指定报表字段*/}
            </Button>
          )}
        </div>
        {SelectValue && SelectValue.key === "part_field_show" && (
          <div className="fields-area">
            {realChooseFields &&
              realChooseFields.length !== 0 &&
              realChooseFields.map((field) => {
                return (
                  <SingleAttribute
                    disabled
                    unique={"display"}
                    key={field.slaveColumnId}
                    widget={field}
                    deleteItem={(widget) => {
                      this.deleteFieldItem(widget, true);
                    }}
                  />
                );
              })}
          </div>
        )}
        <div className={"field-box"} />
        <Modal
          bodyStyle={{ padding: "10px 20px" }}
          maskClosable={false}
          className={"choose-link-field-modal display-field-modal"}
          width={760}
          visible={modalVisible}
          title={messages("basic-10.key246") /*选择报表字段*/}
          onCancel={this.handleModalClose}
          onOk={this.handleSelectLink}
        >
          <div className={"custom-report-data-content"}>
            <div className="link-title">{messages("basic-10.key247") /*已选字段*/}</div>
            <div className="link-list">
              {currentLinkFields.map((field, index) => {
                return (
                  <SingleAttribute
                    disabled
                    onlyDelete
                    unique={"current"}
                    key={field.slaveColumnId}
                    widget={field}
                    index={index}
                    onItemMouseOver={this.handleItemMouseOver}
                    onItemMouseLeave={this.handleItemMouseLeave}
                    deleteItem={this.deleteFieldItem}
                  />
                );
              })}
            </div>
            {currentLinkFields.length === 0 ? (
              <div className="place-holder">{messages("finance-7.key351") /*点击下方字段进行添加*/}</div>
            ) : null}
          </div>
          <div className="title-line">
            <div>
              <span className={"title"}>{permissionDetail.reportName}</span>
              <Button type={"primary"} onClick={this.chooseAll}>
                {messages("basic-10.key248") /*选择所有字段*/}
              </Button>
              <Button style={{ marginLeft: "8px" }} type={"default"} onClick={this.unChooseAll}>
                {messages("basic-10.key249") /*清除所有字段*/}
              </Button>
            </div>
            <div className={`input-search`}>
              <Input.Search
                value={SearchKeyWord}
                placeholder={messages("basic-10.key134") /*搜索字段名*/}
                style={{ width: 240 }}
                onChange={this.modalSearchOnChange}
                onSearch={this.handleSearchModalAttributes}
              />
            </div>
          </div>
          <div className="attr-list-box">
            <div className="muuri-list-box">
              {reportFields &&
                reportFields.length !== 0 &&
                reportFields.map((field, index) => {
                  return (
                    <SingleAttribute
                      disabled
                      unique={"list"}
                      currentSelect={currentLinkFields}
                      onItemClick={(e) => {
                        this.addAttributeToTarget(e, field);
                      }}
                      key={field.id}
                      widget={field}
                      index={index}
                      hoverItem={hoverItem}
                    />
                  );
                })}
            </div>
          </div>
        </Modal>
      </div>
    );
  }
}

VisibleFieldComp.propTypes = {};

export default VisibleFieldComp;
